package com.lz.yz.member.web;

import com.alibaba.fastjson.JSON;
import com.lz.yz.base.entity.ReturnValue;
import com.lz.yz.base.exception.InvalidArgumentException;
import com.lz.yz.member.entity.Withdraws;
import com.lz.yz.member.model.WithdrawModel;
import com.lz.yz.member.service.WithdrawsService;
import com.util.common.ValidateHelper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
* Created by CodeGenerator on 2017/11/16.
*/
@RestController
@RequestMapping("/withdraws")
public class WithdrawsController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WithdrawsService withdrawsService;

    @Autowired
    HttpServletRequest request;

    /**
     * 用户提现
     * @param
     * @return
     */
    @ApiOperation(value="用户提现",response = ReturnValue.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "withdrawModel", value = "提现实体", dataType = "WithdrawModel", paramType = "body"),
            @ApiImplicitParam(paramType = "header",name = "Authorization",value = "Bearer token",defaultValue = "Bearer ")
    })
    @PostMapping
    public ReturnValue insert(@Validated @RequestBody WithdrawModel withdrawModel, BindingResult result)throws Exception{
        Integer accountId  = (Integer)request.getAttribute("accountId");
        String errorMsg = ValidateHelper.firstErrorMessage(result);
        if (errorMsg != null) {
            throw new InvalidArgumentException(errorMsg);
        }
        try {
            return withdrawsService.withdraw(accountId,withdrawModel);
        } catch (Exception e) {
            logger.error("申请提现失败 accountId {}  {} ",accountId, JSON.toJSONString(withdrawModel),e);
            return ReturnValue.generateFalseReturnValue("申请提现失败");
        }
    }
}
